<script lang="ts" setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { ModernAuthenticationRegister } from '@vben/common-ui';
import { ModernAuthLayout } from '@vben/layouts';

import { message } from 'ant-design-vue';

import { registerApi, sendSmsCodeApi } from '#/api';

defineOptions({ name: 'Register' });

const router = useRouter();
const loading = ref(false);

// 发送验证码
async function handleSendCode(mobile: string) {
  try {
    await sendSmsCodeApi({
      mobile,
      smsmode: 1, // 1-注册模式
    });
    message.success('验证码已发送到您的手机');
  } catch (error: any) {
    message.error(error.message || '发送验证码失败，请重试');
    throw error; // 重新抛出错误，阻止倒计时
  }
}

// 提交注册
async function handleSubmit(formData: any) {
  console.log('注册提交:', formData);
  loading.value = true;

  try {
    // 调用真实API注册
    await registerApi({
      userName: formData.username,
      password: formData.password,
      email: formData.email,
      companyName: formData.companyName,
      creditCode: formData.companyCode,
      phone: formData.mobile,
      code: formData.code, // 添加验证码
    });

    message.success('注册成功！');
    // 跳转到注册成功页面
    router.push('/auth/register-success');
  } catch (error: any) {
    message.error(error.message || '注册失败，请重试');
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <ModernAuthLayout
    app-name="工作平台"
    page-title="欢迎注册工作平台"
    page-description="加入我们，开启高效工作之旅"
  >
    <ModernAuthenticationRegister
      :loading="loading"
      :on-send-code="handleSendCode"
      @submit="handleSubmit"
    />
  </ModernAuthLayout>
</template>
